// src/utils/websocket.ts
import { ref } from 'vue';

let socket = ref(null);
let messageHandler = null;

export function initWebSocket() {
  const userId = localStorage.getItem('user_uuid');
  if (!userId) {
    console.error('用户未登录，无法初始化WebSocket');
    return;
  }

  // 创建 WebSocket 连接
  socket.value = new WebSocket(`ws://localhost:3000/ws?userId=${userId}`);

  socket.value.addEventListener('open', () => {
    console.log('WebSocket 连接成功');
  });

  socket.value.addEventListener('message', (event) => {
    try {
      // 确保数据是字符串格式
      const messageStr = event.data.toString();
      const message = JSON.parse(messageStr);
    console.log('收到WebSocket消息:', message);
    
    if (messageHandler) {
      messageHandler(message);
      }
    } catch (error) {
      console.error('处理WebSocket消息错误:', error);
    }
  });

  socket.value.addEventListener('error', (error) => {
    console.error('WebSocket 错误:', error);
  });

  socket.value.addEventListener('close', () => {
    console.log('WebSocket 连接关闭');
  });
}

// 设置消息处理器
export function setMessageHandler(handler) {
  messageHandler = handler;
}

// 发送消息
export function sendSocketMessage(message) {
  if (socket.value && socket.value.readyState === WebSocket.OPEN) {
    const messageStr = JSON.stringify(message);
    socket.value.send(messageStr);
  } else {
    console.warn('WebSocket 未连接，无法发送消息');
  }
}

// 关闭连接
export function closeWebSocket() {
  if (socket.value) {
    socket.value.close();
    socket.value = null;
  }
}